/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Common;

import java.io.*;
import javax.microedition.rms.*;
import Constants.*;

/**
 *
 * @author Hmong
 */
public class RMSSettingsLoader {
    private RecordStore _RecordStore = null;

    private String _Language = null;

    protected RMSSettingsLoader(){
    }

    public static RMSSettingsLoader CreateInstance(){
        RecordStore recordStore;

        try{
            recordStore = RecordStore.openRecordStore(Constant.RecordStore_Name, true);
        } catch(RecordStoreException ex){
            recordStore = null;
        }

        if (null == recordStore){
            System.out.println("[X] Configer CreateInstance fail.");
            return null;
        }
        
        RMSSettingsLoader instance = new RMSSettingsLoader();
        instance._RecordStore = recordStore;

        System.out.println("[O] Configer CreateInstance Successful.");
        return instance;
    }

    public String GetLanguage(){
        // 尝试读取RMS中用户选择的语言设置
        String strLang;
        try{
            //int nSize = this._RecordStore.getRecordSize(Constant.RecordId_Language);
            byte[] btArrData = this._RecordStore.getRecord(0);
            _Language = new String(btArrData);
        } catch(RecordStoreException ex){
            _Language = null;
        }

        // 否则返回null
        return null;
    }

    public boolean SetLanguage(String lang){
        byte[] btArrData = lang.getBytes();
        boolean bRet = true;

        try{
            int nRecordsCount = this._RecordStore.getNumRecords();
            if (0 == nRecordsCount)
                this._RecordStore.addRecord(btArrData, 0, btArrData.length);
            else
                this._RecordStore.setRecord(0, btArrData, 0, btArrData.length);
        }  catch(RecordStoreNotOpenException noex){
            bRet = false;
        } catch(RecordStoreException ex){
            bRet = false;
        }

        return bRet;
    }
}
